const defaultHeaderStyle = {
  fontColor: '000000',
  horizontalAlignment: 'left',
  fontFamily: '等线',
  bold: false
}

const defaultCellStyle = {
  fontColor: '000000',
  horizontalAlignment: 'left',
  fontFamily: '等线',
  width: '18'
}

const DefaultMergedStyle = {
  fontColor: '000000',
  horizontalAlignment: 'left',
  fontFamily: '等线',
  bold: false,
  wrapText: true
}

const getOutput = (headers, tableData, isRangeMode, exchangeAxis, mergeVal) => {
  return XlsxPopulate.fromBlankAsync().then(workbook => {
    const sheet = workbook.sheet(0)
    if (mergeVal) { // 合并单元格
      sheet.row(mergeVal.line).height(mergeVal.height)
      const mergeStyle = Object.assign({}, DefaultMergedStyle, mergeVal.style)
      sheet.range(mergeVal.region).value(mergeVal.content).merged(true).style(mergeStyle)
    }

    if (headers && headers.length) {
      for (let index = 0; index < headers.length; index++) {
        var header = headers[index]
        var name = header.label
        var style = Object.assign({}, defaultHeaderStyle, header.headerStyle)
        var width = 8.5

        if (mergeVal) {
          sheet.cell(mergeVal.col, index + 1).value(name).style(style)
        } else {
          if (exchangeAxis) {
            sheet.cell(index + 1, 1).value(name).style(style)
          } else {
            sheet.column(index + 1).width(width || 8.5)
            sheet.cell(1, index + 1).value(name).style(style)
          }
        }
      }
    }

    if (headers && headers.length && tableData && tableData.length) {
      for (let index = 0; index < tableData.length; index++) {
        for (let indexInHeaders = 0; indexInHeaders < headers.length; indexInHeaders++) {
          const header = headers[indexInHeaders]
          const width = header.width
          const prop = header.prop
          const style = Object.assign({}, defaultCellStyle, header.style)

          if (exchangeAxis) {
            sheet.column(index + 1).width(width || 8.5)
            sheet.cell(indexInHeaders + 1, index + 2).value(tableData[index][prop])
          } else {
            sheet.cell(index + 2, indexInHeaders + 1).value(tableData[index][prop])
          }
        }
      }
    }
    return workbook.outputAsync({ type: null })
  })
}

onmessage = function ({ data: { headers, tableData, isRangeMode, exchangeAxis, mergeVal } }) {
  getOutput(headers, tableData, isRangeMode, exchangeAxis, mergeVal).then((blob) => {
    postMessage(blob)
  })
}
